package com.lineage.server.timecontroller.pc;

import com.lineage.config.Config;
import com.lineage.echo.ClientExecutor;
import com.lineage.list.OnlineUser;
import com.lineage.server.model.Instance.L1PcInstance;
import com.lineage.server.thread.PcOtherThreadPool;
import java.util.Collection;
import java.util.Iterator;
import java.util.TimerTask;
import java.util.concurrent.ScheduledFuture;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class PcAutoSaveTimer extends TimerTask {
  private static final Log _log = LogFactory.getLog(PcAutoSaveTimer.class);
  
  private ScheduledFuture<?> _timer;
  
  public void start() {
    int timeMillis = 60000;
    this._timer = PcOtherThreadPool.get().scheduleAtFixedRate(this, 60000L, 60000L);
  }
  
  public void run() {
    try {
      Collection<ClientExecutor> allClien = OnlineUser.get().all();
      if (allClien.isEmpty())
        return; 
      Iterator<ClientExecutor> iter = allClien.iterator();
      while (iter.hasNext()) {
        ClientExecutor client = iter.next();
        int time = client.get_savePc();
        if (time == -1)
          continue; 
        time--;
        save(client, Integer.valueOf(time));
      } 
    } catch (Exception e) {
      _log.error("人物资料自动保存时间轴异常重启", e);
      PcOtherThreadPool.get().cancel(this._timer, false);
      PcAutoSaveTimer restart = new PcAutoSaveTimer();
      restart.start();
    } 
  }
  
  private void save(ClientExecutor client, Integer time) {
    try {
      if (client.get_socket() == null)
        return; 
      if (time.intValue() > 0) {
        client.set_savePc(time.intValue());
      } else {
        client.set_savePc(Config.AUTOSAVE_INTERVAL);
        L1PcInstance pc = client.getActiveChar();
        if (pc != null)
          pc.save(); 
      } 
    } catch (Exception e) {
      _log.debug("执行人物资料存档处理异常 帐号:" + client.getAccountName());
    } 
  }
}
